package program.queue;

/**
 * 使用链表实现队列.
 * 1. 使用了head. tail指针.
 * 2. 使用tail进行入队.
 * 3. 使用head进行出队.
 * 4. head就是第一个元素; tail为最后一个元素.
 *
 * 好处:
 *  1. 保证了入队和出队的时间复杂度都是O(1).
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        private E data;
        private Node next;

        public Node() {
            this(null, null);
        }

        public Node(E data) {
            this(data, null);
        }

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

        @Override
        public String toString() {
            return data.toString();
        }
    }

    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node(e);
            head = tail;
        } else {
            tail.next = new Node(e);
            tail = tail.next;
        }

        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty!");
        }

        Node delNode = head;
        head = head.next;
        delNode.next = null;
        if (head == null) {
            // 注意队列中就只有一个元素时, head和tail指向同一个数据; 那么head==null时, 也需要修改tail;
            // 否则会导致, tail还指向原来的数据.
            tail = null;
        }

        size--;
        return delNode.data;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty!");
        }

        return head.data;
    }

    @Override
    public String toString() {
        StringBuilder resultStr = new StringBuilder();
        int size = getSize();
        resultStr.append(String.format("Queue size:%d\n", size));
        resultStr.append("front [");
        Node cur = head;
        while (cur != null) {
            resultStr.append(cur).append("->");
            cur = cur.next;
        }

        resultStr.append("NULL");
        resultStr.append("]tail");
        return resultStr.toString();
    }
}
